package com.geeaks.learn.guava;

import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.util.concurrent.RateLimiter;

public class RatelimiterTest {
	
	static int maxRequest = 100;
	
	static AtomicInteger nowRequest = new AtomicInteger(0);
	
	static void request() {
		for (;;) {
			int currentReq = nowRequest.get();
			if (currentReq >= maxRequest) {
				return;
			}
			if (nowRequest.compareAndSet(currentReq, currentReq + 1)) {
				break;
			}
		}
		// 调用接口
		try {
			System.out.println("invoke method");
		} finally {
			nowRequest.decrementAndGet();
		}
	}
	
	public static void main(String[] args) {
		request();
	}
	
	static void testb() {
		RateLimiter rateLimiter = RateLimiter.create(1);
		double waitTime = rateLimiter.acquire(10);
		System.out.println(System.currentTimeMillis() / 1000 + " , " + waitTime);
		waitTime = rateLimiter.acquire(1);
		System.out.println(System.currentTimeMillis() / 1000 + " , " + waitTime);
	}
	
	static void testa() {
		// create方法传入的是每秒生成令牌的个数
		RateLimiter rateLimiter = RateLimiter.create(1);
		for (int i = 0; i < 5; i++) {
			// acquire方法传入的是需要的令牌个数，当令牌不足时会进行等待，该方法返回的是等待的时间
			double waitTime = rateLimiter.acquire(1);
			System.out.println(System.currentTimeMillis() / 1000 + " , " + waitTime);
		}
	}
}
